<?php

namespace app\commands;

use app\models\Comments;
use yii\console\Controller;

class DanmuController extends Controller
{

    /**
     * 弹幕队列入库
     */
    public function actionList()
    {
        $startTime = time();
        $redis = \Yii::$app->get('redis');

        while (true) {
            $nowTime = time();

            if (abs($startTime - $nowTime) > 50) {
                break;
            }

            $queue = $redis->rPop('danmu');
            $queueHash = json_decode($queue, true);

            if (isset($queueHash['msg']) && isset($queueHash['time'])) {
                try {
                    Comments::add($queueHash['msg'], $queueHash['time']);
                } catch (\Exception $e) {
                    echo "{$e->getMessage()}\n";
                }
            } else {
                usleep(100 * 1000);
            }
        }
    }

}